<template>
    <div>
        <s-table :search-params="searchParams" :columns="columnsAction" :async-fc="page" ref="table">
            <template #tableHeader>
                <t-button v-has-perms="['system:user:manage']" @click="insert">新增信息</t-button>
            </template>
        </s-table>
        <t-dialog header="用户管理" v-model:visible="modalOpen" width="50%" @confirm="onModalSubmit">
            <t-form ref="submitFormRef" :rules="rules" :data="submitForm">
                <t-row style="width: 100%;" :gutter="[16, 24]">
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.username')" name="username">
                            <t-input v-model="submitForm.username" :placeholder="t('pages.sysUser.usernamePlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col v-if="!submitForm.id" :span="6">
                        <t-form-item :label="t('pages.sysUser.password')" name="password">
                            <t-input type="password" v-model="submitForm.password" :placeholder="t('pages.sysUser.passwordPlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.sex')" name="sex">
                            <t-select v-model="submitForm.sex" :options="sexOptions" :placeholder="t('pages.sysUser.sexPlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.nickname')" name="nickname">
                            <t-input v-model="submitForm.nickname" :placeholder="t('pages.sysUser.nicknamePlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.phone')" name="phone">
                            <t-input v-model="submitForm.phone" :placeholder="t('pages.sysUser.phonePlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.email')" name="email">
                            <t-input v-model="submitForm.email" :placeholder="t('pages.sysUser.emailPlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.role')" name="role">
                            <t-select v-model="submitForm.role" multiple :options="roleOptions" :placeholder="t('pages.sysUser.rolePlaceholder')"/>
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.avatar')" name="avatar">
                            <s-upload v-model:value="submitForm.avatar" value-type="data" :limit="1" :tip="t('pages.sysUser.avatarPlaceholder')" />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.remarks')" name="remarks">
                            <t-textarea :autosize="{ minRows: 5, maxRows: 5 }" v-model="submitForm.remarks" :placeholder="t('pages.sysUser.remarksPlaceholder')"/>
                        </t-form-item>
                    </t-col>
                </t-row>
            </t-form>
        </t-dialog>
    </div>
</template>
<script setup lang="ts">
/*****                                          引用部分开始                                          *****/
import {onMounted, ref} from "vue";
import { t } from "@/locales";
import { useUserStore } from "@/store";
import STable from '@/components/s-table/index.vue';
import SUpload from '@/components/s-upload/index.vue';
import { searchParams, columns, rules, sexOptions } from './props';
import { page, update as updateApi, insert as insertApi, deleteById } from "@/api/sysUser";
import { FormInstanceFunctions, Link, Space, MessagePlugin, DialogPlugin } from "tdesign-vue-next";
import {getOptions} from "@/api/sysRole";
/*****                                          引用部分结束                                          *****/

/*****                                          属性定义部分开始                                          *****/
const user = useUserStore();
const submitForm = ref({});
const roleOptions = ref([]);
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<TableInstanceFunctions>(null);
/*****                                          属性定义部分结束                                          *****/


const columnsAction = columns.concat([{
    align: 'left',
    fixed: 'right',
    colKey: 'op',
    title: t('components.commonTable.operation'),
    cell: (h, {row}) => h(Space, {}, [
        h(Link, {
            theme: 'primary',
            onClick: () => {
                // 为了下拉回显，赋值由 [{ label:'', value: '' }] ==> ['', '']
                row.role = row.roles.map(i => i.value);
                submitForm.value = row;
                modalOpen.value = true;
            }
        }, '修改'),
        h(Link, {
            theme: 'danger',
            onClick: () => {
                const confirmDialog = DialogPlugin.confirm({
                    header: `提示`,
                    body: `删除后，标记为${row.id}的所有信息将被清空，且无法恢复`,
                    confirmBtn: {
                        content: '提交',
                        theme: 'primary',
                        loading: false,
                    },
                    theme: 'warning',
                    onConfirm: async () => {
                        confirmDialog.update({ confirmBtn: { content: '提交中', loading: true } });
                        await deleteById(row.id);
                        MessagePlugin.success('删除成功！');
                        table.value.onSearch();
                        confirmDialog.update({ confirmBtn: { content: '提交', loading: false } });
                        confirmDialog.hide();
                    },
                })
            }
        }, '删除'),
    ])
}]);


/*****                                          页面方法开始                                          *****/
const insert = () => {
    modalOpen.value = true;
    submitForm.value = {
        sex: 2,
    };
}

/**
 * 提交表单
 */
const onModalSubmit = async () => {
    const valid = await submitFormRef.value.validate();
    submitForm.value = {
        ...submitForm.value,
        roles: submitForm.value.role.map(i => ({ value: i })),
    }
    if (valid) {
        if (submitForm.value.id) {
            await updateApi(submitForm.value);
        } else {
            await insertApi(submitForm.value);
        }
        MessagePlugin.success('操作成功！');
        modalOpen.value = false;
        table.value.onSearch();
    }
}

onMounted(async () => {
    const data = await getOptions();
    roleOptions.value = data;
})

/*****                                          页面方法结束                                          *****/
</script>
